import { ExceptionHandler } from './../../../../../../handler/exception.handler';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { DepartmentService } from 'src/app/services/department.service';
import { OrganizationService } from 'src/app/services/organization.service';

@Component({
  selector: 'zepride-edit-department-modal',
  templateUrl: './edit-department-modal.component.html',
  styleUrls: ['./edit-department-modal.component.less']
})
export class EditDepartmentModalComponent implements OnInit {
  @Input() departmentInfo: any = {};
  @Input() organizationId: string;
  formGroup: FormGroup;
  orgTreeNode;
  userList: any[] = [];
  constructor(
    private fb: FormBuilder,
    private departmentService: DepartmentService,
    private orgSvr: OrganizationService,
    private modal: NzModalRef,
    private msg: NzMessageService
  ) {

  }

  async ngOnInit() {
    this.formGroup = this.fb.group({
      name: [this.departmentInfo.name, [Validators.required]],
      description: [this.departmentInfo.description],
      leaderPerson: [this.departmentInfo.leaderPerson]
    });

    await this.getOrgTreeNode();
    await this.getOrgUserTree();
  }

  private async getOrgTreeNode() {
    try {
      let result = await this.orgSvr.getOrganizationTrees({ objectId: this.organizationId });
      this.orgTreeNode = result[0];
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  private async getOrgUserTree() {
    try {
      this.userList = await this.orgSvr.getOrganizationTrees({ organizationId: this.organizationId, objectName: "User" });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }


  async ok() {
    try {
      for (let key in this.formGroup.controls) {
        this.formGroup.controls[key].markAsTouched();
        this.formGroup.controls[key].updateValueAndValidity();
        this.departmentInfo[key] = this.formGroup.controls[key].value;
      }
      if (this.formGroup.valid) {
        this.departmentInfo.organizationId = this.organizationId;
        this.departmentInfo.orgTree = {
          parentId: this.orgTreeNode.id
        };
        if (this.departmentInfo.id) {
          await this.departmentService.updateDepartment(this.departmentInfo);
        }
        else {
          await this.departmentService.createDepartment(this.departmentInfo);
        }
        this.modal.close('ok');
      }

    } catch (error) {
      console.log(error);
      this.msg.error(error.error.message);
    }
  }
  cancel() {
    this.modal.close('cancel');
  }
}
